import { DB } from "../db"
import { UserDefine } from "../../../kds-base-define/src/UserDefine"

let redis = DB.redis
let tableName = "t_user_grouprecord"
type RecordPOType = {
	infos:{
		groupID:number,
		record:UserDefine.GameRecord,
	}[]
}
async function getUserPOData(userID:number) {
	let data:RecordPOType = await redis.hget(tableName,userID.toString(),true)
	return data 
}
async function setUserPOData(userID:number,data:RecordPOType) {
	await redis.hset(tableName,userID.toString(),data,true)
}

async function getGroupRecord(h:string,userID:number,groupID:number) {
	let data = await getUserPOData(userID)
	if(data) {
		let info = data.infos.find(v=>v.groupID == groupID)
		return info != null ? info.record : null  
	}
	return null
}

async function updateGroupRecord(h:string,userID:number,groupID:number,record:UserDefine.GameRecord) {
	let data = await getUserPOData(userID)
	if(data == null) {
		data = {
			infos:[]
		}
	}
	let idx = data.infos.findIndex(v=>v.groupID == groupID)
	if(idx < 0) {
		data.infos.push({
			groupID:groupID,
			record:record
		})
	} else {
		data.infos[idx].record = record
	}
	setUserPOData(userID,data)
	return true 
}

async function removeGroupRecord(h:string,userID:number,groupID:number) {
	let data = await getUserPOData(userID)
	if(data == null) {
		return true 
	}
	let idx = data.infos.findIndex(v=>v.groupID == groupID)
	if(idx < 0) {
		return true 
	}
	data.infos.splice(idx,1)
	await setUserPOData(userID,data)
	return true 
}

async function getAllRecord(h:string,userID:number) {
	let data = await getUserPOData(userID)
	let ret:UserDefine.UserGameRecordData = {
		groupRecords:[]
	}
	if(data == null) {
		return ret 
	}
	for(let info of data.infos) {
		ret.groupRecords.push({
			groupID:info.groupID,
			record:info.record
		})
	}
	return ret 
}

export let RpcUserGameRecord = {
	get:getGroupRecord,
	update:updateGroupRecord,
	remove:removeGroupRecord,
	getAll:getAllRecord,
}